<template>
  <div class="home">
    <SearchBar
      disabled
      @onClick="onSearchBarClick(hotSearch.keyword)"
      :hotSearch="hotSearch.keyword"
    ></SearchBar>
    <HomeCard
      :data="homeCard"
      @onBookClick="onBookClick"
    ></HomeCard>
    <HomeBanner
      :img="banner.img"
      :title="banner.title"
      :subTitle="banner.subTitle"
      @onClick="onBannerClick"
    ></HomeBanner>
    <HomeBook
      title="为你推荐"
      btnText="换一批"
      :row="1"
      :col="3"
      :data="recommend"
      mode="col"
      @onMoreClick="()=>recommendChange('recommend')"
      @onBookClick="onBookClick"
    ></HomeBook>
    <HomeBook
      title="免费阅读"
      btnText="换一批"
      :row="2"
      :col="2"
      :data="freeRead"
      mode="row"
      @onMoreClick="recommendChange('freeRead')"
      @onBookClick="onBookClick"
    ></HomeBook>
    <HomeBook
      title="当前最热"
      btnText="换一批"
      :row="1"
      :col="4"
      :data="hotBook"
      mode="col"
      @onMoreClick="recommendChange('hotBook')"
      @onBookClick="onBookClick"
    ></HomeBook>
    <HomeBook
      title="分类"
      btnText="查看全部"
      :row="3"
      :col="2"
      :data="category"
      mode="category"
      @onMoreClick="onCategoryMoreClick(category)"
      @onBookClick="onBookClick"
    ></HomeBook>
    <div
      class="auth"
      v-if="!isAuth"
    >
      <Auth @getUserInfo="init"></Auth>
    </div>
  </div>
</template>

<script>
import SearchBar from '../../components/home/SearchBar'
import ImageView from '../../components/base/ImageView'
import HomeCard from '../../components/home/HomeCard'
import HomeBanner from '../../components/home/HomeBanner'
import HomeBook from '../../components/home/HomeBook'
import Auth from '../../components/base/Auth'
import { getHomeData, getHomeHomeData, register } from '../../api/index.js'
import { getSetting, getUserInfo, setStorageSync, getStorageSync, getOpenId, showLoading, hideLoading } from '../../api/wechat.js'
export default {
  components: {
    SearchBar,
    ImageView,
    HomeCard,
    HomeBanner,
    HomeBook,
    Auth
  },
  beforeMount () {
    this.init()
  },
  data () {
    return {
      hotSearch: {},
      homeCard: {},
      shelf: [],
      recommend: [],
      freeRead: [],
      hotBook: [],
      category: [],
      banner: {},
      shelfCount: 0,
      // 为真，不显示授权页面
      isAuth: true
    }
  },
  methods: {
    // 获取首页的数据
    async getHomeDate (openId, userInfo) {
      // 我也不想解构那么多层啊啊啊啊啊啊啊！！！！！
      const { data: { data: { hotSearch,
        shelf,
        recommend,
        freeRead,
        hotBook,
        category,
        banner,
        shelfCount } } } = await getHomeData({ openId })
      // 对数据进行验证，看接口是否返回数据，随便一个数据
      if (shelf) {
        this.hotSearch = hotSearch
        this.recommend = recommend
        this.freeRead = freeRead
        this.hotBook = hotBook
        this.category = category
        this.banner = banner
        this.homeCard = {
          userInfo,
          bookList: shelf,
          num: shelfCount
        }
        hideLoading()
      } else {
        // 接口返回数据失败
        hideLoading()
        // TODO 抛出异常
        console.log('index-getHomeDate')
      }
    },
    // 点击换一批的响应函数
    async recommendChange (key) {
      const { data: { data } } = await getHomeHomeData(key)
      // BUG 点击当前最热的换一批的时候，有事还会闪烁(位置移动)
      switch (key) {
        case 'recommend':
          this.recommend = data
          break
        case 'freeRead':
          this.freeRead = data
          break
        case 'hotBook':
          this.hotBook = data
          break

        default:
          break
      }
      this.key = data
    },
    onSearchBarClick (hotSearch) {
      this.$router.push({ path: '/pages/search/main', query: { hotSearch } })
    },
    onBannerClick () {
      console.log('index', 'onBannerClick')
      // TODO 跳转的页面(页面还没写)
    },
    onBookClick (e) {
      // e是传递过来的图书信息
      this.$router.push({ path: '/pages/detail/main', query: e })
    },
    // 点击分类的查看全部，跳转到全部分类页面
    onCategoryMoreClick () {
      this.$router.push({ path: '/pages/categoryList/main' })
    },
    getSetting () {
      getSetting('userInfo',
        () => {
          this.isAuth = true
          showLoading('正在加载')
          this.getUserInfo()
        }, () => {
          console.log('getSetting，用户还未授权')
          this.isAuth = false
        })
    },
    getUserInfo (res) {
      const onOpenIdComplete = async (openId) => {
        const userInfo = getStorageSync('userInfo')
        await register(openId, userInfo)
        //  微信用户名是特殊符号(改了用户名，后就可以注册成功了)，会注册失败
        this.getHomeDate(openId, userInfo)
      }
      getUserInfo(
        (userInfo) => {
          setStorageSync('userInfo', userInfo)
          const openId = getStorageSync('openId')
          if (!openId || openId.length === 0) {
            // ASK 下面这一句，不明白参数怎么传递过来的，onOpenIdComplete的参数哪来的
            // getOpenId的callback，会传进来
            getOpenId(onOpenIdComplete)
          } else {
            // 已经获取openid
            const openId = getStorageSync('openId')
            onOpenIdComplete(openId)
          }
        },
        () => {
          console.log('getUserInfo-fail....')
        })
    },
    init () {
      this.getSetting()
    }
  }
}
</script>

<style lang="scss" scoped></style>
